package com.tyc.log.interceptor;

import cn.hutool.core.util.StrUtil;
import com.tyc.log.common.Constant;
import com.tyc.log.util.TraceLogUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 日志拦截器添加 traceId
 * 若用到远程调用需要 openfeign 或者 dubbo 添加对应的拦截器放入traceId
 * @author tyc
 * @version 1.0
 * @date 2022-12-27 09:59:33
 */
@Slf4j
@Component
public class LogInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String traceId = request.getHeader(Constant.TRACE_ID);
        if(StrUtil.isEmpty(traceId)){
            traceId = TraceLogUtils.getTraceId();
        }
        MDC.put(Constant.TRACE_ID,traceId);
        return true;
    }
}
